package xyz.penghaonan.p2plib.helper.sockethelper;

import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.penghaonan.appframework.utils.WeakObservableList;

import xyz.penghaonan.p2plib.P2PManager;
import xyz.penghaonan.p2plib.helper.message.MsgReceiver;

/**
 * @Author: duke
 * @DateTime: 2019-05-26 10:53
 * @Description:
 */
public abstract class SocketBase {
    protected static final int SERVER_PORT = 65432;
    // 品牌-型号
    protected static final String PHONE_INFO = Build.BRAND + " - " + Build.MODEL;

    public interface OnReceiveListener {
        void onReceived(String text);
    }

    private final WeakObservableList<OnReceiveListener> listenerList = new WeakObservableList<>();
    private boolean isReleased;

    public SocketBase() {
        addReceiveListener(new MsgReceiver());
    }

    public void addReceiveListener(OnReceiveListener listener) {
        listenerList.addListener(listener);
    }

    public void removeReceiveListener(OnReceiveListener listener) {
        listenerList.removeListener(listener);
    }

    protected void postToUI(String text) {
        Message message = Message.obtain(handler);
        message.obj = text;
        message.sendToTarget();
    }

    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            if (msg == null || msg.obj == null || listenerList.observerCount() == 0) {
                return;
            }
            listenerList.iterate(new WeakObservableList.OnIterator<OnReceiveListener>() {
                @Override
                protected boolean onIterator(OnReceiveListener item) {
                    item.onReceived(msg.obj.toString());
                    return false;
                }
            });
        }
    };

    public void release() {
        isReleased = true;
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        listenerList.clear();
    }

    public boolean isReleased() {
        return isReleased;
    }
    abstract public boolean send(String text);
}
